﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;

namespace Attendance
{
    class CardPort
    {
        public SerialPort serialPort { get; set; }
        public string port { get; set; }
        public string s100;
        private string[] ports;
        public string CardMac { get; set; }

        /*
         * 
         */
        public delegate void DataReceivedRegister(object sender, SerialDataReceivedEventArgs e);

        public void DataReceived(DataReceivedRegister dataReceived)
        {
            this.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(ReadPort);
            this.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(dataReceived);
        }

        public CardPort()
        {
        }

        public bool ChkPorts()
        {
            ports = SerialPort.GetPortNames();
            if (ports.Length == 0)
                throw new Exception("没有检查到读卡器！");
            return true;
        }

        private void SelectPort(string port)
        {
            this.port = port;
        }

        public bool OpenPorts()
        {
            if (ports.Length == 0)
                this.ChkPorts();
            serialPort = new SerialPort(ports[0], 9600);
            serialPort.Open();
            //serialPort.DataReceived += new SerialDataReceivedEventHandler(ReadPort);
            CardMac = "";
            return true;
        }

        public void ClosePorts()
        {
            //serialPort.DataReceived -= new SerialDataReceivedEventHandler(ReadPort);
            serialPort.Close();
        }

        public void ReadPort(Object sender, SerialDataReceivedEventArgs e)
        {
            GetCardMac();
        }

        private string GetCardMac()
        {
            //获取物理卡号过程
            s100 = "";
            Thread.Sleep(1000);
            byte[] readBuffer = new byte[4];
            serialPort.Read(readBuffer, 0, 4);
            s100 = ByteArrayToHexString(readBuffer);
            s100 = s100.Replace(" ", "");

            //十六进制的物理卡号转成十进制
            s100 = Convert.ToInt64(s100, 16).ToString();
            CardMac = s100;
            //throw new Exception(CardMac);
            return CardMac;
            //MessageBox.Show(s100);
        }

        private static string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            string a = sb.ToString();
            return sb.ToString().ToUpper();
        }
    }
}
